package com.disk.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.disk.domain.User;
import com.disk.domain.UserRole;
import com.disk.handleResult.DiskMessage;
import com.disk.handleResult.Result;
import com.disk.mapper.MenuMapper;
import com.disk.mapper.UserMapper;
import com.disk.mapper.UserRoleMapper;
import com.disk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public User getByName(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        return userMapper.selectOne(lambdaQueryWrapper);
    }

    public Integer getRoleByUserId(Integer id){
        Integer roleId = menuMapper.selectRoleByUserId(id);
        return roleId;
    }

    @Override
    public Result register(User user) {
        UserRole userRole=new UserRole(user.getId(),1);
        int insertRole = userRoleMapper.insert(userRole);

        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        int insert = userMapper.insert(user);
        return insert==1?new Result(true, DiskMessage.REGISTER_SUCCESS)
                :new Result(false,DiskMessage.REGISTER_FAILD);
    }
}
